<?php

namespace app\admin\controller\coupon;

use app\admin\model\Shop;
use app\admin\model\Shopdou;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Dou extends Backend
{

    /**
     * Dou模型对象
     * @var \app\admin\model\coupon\Dou
     */
    protected $model = null;
    protected $searchFields = 'shop.name';
    protected $appKey = "";
    protected $secret = "";
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\coupon\Dou;
        $this->appKey = "awoh1q4tfg29z1yv";
        $this->secret = "b8976219b329b01d543e76a83c923720";
        $this->view->assign("couponType", $this->model->getCouponType());

    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['shop'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $m) {
                $roomList = $m['room_id'];
                $roomType = $m['type'];
                if (!empty($roomList)) {
                    $roomList = json_decode($roomList, true);
                    if ($roomType == 'qp') {
                        //查询包厢名称
                        $roomName = Db::name('shop_room')->where('id', 'in', $roomList)->field('name')->select();
                    } else{
                        //查询台桌名称
                        $roomName = Db::name('shop_table')->where('id', 'in', $roomList)->field('name')->select();
                    }
                    $roomArr = array();
                    foreach ($roomName as $n) {
                        $roomArr[] = $n['name'];
                    }
                    $m['room_name'] = $roomArr;
                } else {
                    $m['room_name'] = '';
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        $type = $params['type'];
        $room_id = $params['room_id'];
        $table_id = $params['table_id'];

        unset($params['price']);
        if($type == 'qp'){
            if(empty($room_id)){
                $this->error('包厢不能为空');
            }
            $params['room_id'] = '[' . $params['room_id'] . ']';
            unset($params['table_id']);
            unset($params['sku_name']);
        }elseif ($type == 'tq'){
            if(empty($table_id)){
                $this->error('台桌不能为空');
            }
            $params['room_id'] = '[' . $params['table_id'] . ']';
            unset($params['table_id']);
            unset($params['sku_name']);
        }else{
            $this->error('未知券的类型');
        }

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $this->model->where('id', $ids)->update($params);
            //$result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 一键同步
     */
    public function sync()
    {

        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
    }

    public function syncCouponInfo()
    {
        $shop_id = $this->request->param('shop_id');
        $cursor = $this->request->param('cursor');
        $shopModel = new Shop();
        $shop = $shopModel->where('id', $shop_id)->find();
        $dou_id = $shop['dou_id'];
        if (empty($dou_id)) {
            $val['code'] = 0;
            $val['msg'] = '请联系客服，抖音暂未配置';
            $val['data'] = [];
            return json($val);
        }

        $tokenUrl = "https://open.douyin.com/oauth/client_token/";
        $tokenReq = array();
        $tokenReq["client_key"] = $this->appKey;
        $tokenReq["client_secret"] = $this->secret;
        $tokenReq["grant_type"] = "client_credential";

        $result = $this->curl_post($tokenUrl, $tokenReq);
        $token = $result['data']['access_token'];

        $account_id = $dou_id;
        $url = "https://open.douyin.com/goodlife/v1/goods/product/online/query/?status=1&goods_creator_type=1&count=50&account_id=" . $account_id;

        if ($cursor != 0) {
            $url = "https://open.douyin.com/goodlife/v1/goods/product/online/query/?status=1&cursor=" . $cursor . "&goods_creator_type=1&count=50&account_id=" . $account_id;
        }

        error_log("==admin=url==" . $url);
        $result = $this->http_curl_get($url, $token);
        try {
            $product = $result['data']['products'];
            $has_more = $result['data']['has_more'];
            $next_cursor = $result['data']['next_cursor'];
        }catch (Exception $e){
            $val['code'] = 0;
            $val['msg'] = $result['data']['description'];
            $val['data'] = [];
            return json($val);
        }

        if (!$has_more) {
            $next_cursor = 0;
        }

        $poi_id = $shop['poi_id'];
        $shopDouModel = new Shopdou();
        $ret = array();
        foreach ($product as $key => $val) {

            $pois = $val['product']['pois'];
            $sku = $val['sku'];
            $skuId = $sku['sku_id'];
            $skuName = $sku['sku_name'];
            $isAdd = 0;
            foreach ($pois as $k => $v) {
                if ($v['poi_id'] == $poi_id) {
                    $isAdd = 1;
                }
            }
            if ($isAdd == 1) {
                $db = array();
                $db['sku_id'] = $skuId;
                $db['sku_name'] = $skuName;
                $db['shop_id'] = $shop_id;
                $db['price'] = $sku['actual_amount'] / 100;
                $ret[] = $db;
                $skuDb = $shopDouModel->where('shop_id', $shop_id)->where('sku_id', $skuId)->find();
                if ($skuDb) {
                    $shopDouModel->where('id', $skuDb['id'])->update($db);
                } else {
                    $shopDouModel->insert($db);
                }
            } else {
                $shopDouModel->where('shop_id', $shop_id)->where('sku_id', $skuId)->delete();
            }
        }

        $val['code'] = 1;
        $val['msg'] = '同步成功';
        $val['data'] = $next_cursor;
        return json($val);
    }

    //post请求
    public function curl_post($url, $postdata)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Expect:'
        )); // 解决数据包大不能提交
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
        return $tmpInfo;
    }


    //post请求
    public function curl_post2($url, $postdata, $token)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测

        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', "access-token: " . $token));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
        return $tmpInfo;
    }


    public function http_curl_get($url, $token)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_TIMEOUT, 5000);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', "access-token: " . $token));

        $tmpInfo = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
        return $tmpInfo;
    }

}
